<template>
  <div class="page-wrapper">
    <!-- 加密水印容器 -->
    <div class="watermarks">
      <div v-for="index in 40" :key="index" class="watermark" :style="getWatermarkStyle(index)">ZBT</div>
    </div>

    <!-- 顶部操作区域 -->
    <div class="top-bar">
      <button class="back-btn" @click="goBack">返回</button>
      <button class="export-btn" @click="exportToExcel">导出为Excel</button>
      <button class="export-btn" @click="exportToPdf">导出为PDF</button>
      <button class="allEdit-btn" :style="{ background: allEditStates ? 'brown' : '#00aaff' }"
        @click="handleAllEditStates">
        {{ allEditStates ? '取消编辑' : '编辑' }}
      </button>
    </div>

    <div class="profile-container">
      <h2 class="profile-title">{{ profile.name || '--' }}的个人档案</h2>

      <!-- 个人照片 -->
      <div class="profile-header">

        <!-- 优先显示用户上传的头像 -->
        <!-- <img v-if="user.profilePicture" :src="user.profilePicture" alt="个人照片" class="profile-image" /> -->

        <!-- 如果没有上传头像，则根据性别选择默认头像 -->
        <!-- <img v-else-if="user.gender === 1" src="@/assets/man-image.jpg" alt="男性默认头像" class="profile-image" /> -->
        <img v-if="profile.gender === 1" src="@/assets/man-image.jpg" alt="男性默认头像" class="profile-image" />


        <img v-else-if="profile.gender === 0" src="@/assets/man-image.jpg" alt="女性默认头像" class="profile-image" />

        <!-- 如果性别未知或不符合预期值，则使用通用默认头像 -->
        <img v-else src="@/assets/images/person.jpg" alt="默认头像" class="profile-image" />
      </div>

      <!-- 基本信息 -->
      <div class="profile-section">
        <h3>基本信息
          <button v-if="allEditStates" class="edit-btn"
            @click="editStates.basicInfo ? saveSection('basicInfo') : toggleEdit('basicInfo')">
            {{ editStates.basicInfo ? '保存' : '编辑' }}
          </button>
        </h3>
        <div v-if="!editStates.basicInfo" class="profile-grid">
          <p><strong>姓名:</strong> {{ profile.name || '--' }}</p>
          <p><strong>性别:</strong> {{ profile.gender === 1 ? '男' : '女' }}</p>
          <p><strong>身份证号码:</strong> {{ profile.idCard || '--' }}</p>
          <p><strong>政治面貌:</strong> {{ profile.politicalAffiliation || '--' }}</p>
          <p><strong>出生年月:</strong> {{ profile.birthDate || '--' }}</p>
          <p><strong>民族:</strong> {{ profile.nationality || '--' }}</p>
          <p><strong>身高:</strong> {{ profile.height ? profile.height + ' cm' : '--' }}</p>
          <p><strong>体重:</strong> {{ profile.weight ? profile.weight + ' kg' : '--' }}</p>
          <p><strong>视力:</strong> {{ profile.vision || '--' }}</p>
          <p><strong>籍贯:</strong> {{ profile.nativePlace || '--' }}</p>
          <p><strong>联系方式:</strong> {{ profile.telephone || '--' }}</p>
          <p><strong>QQ:</strong> {{ profile.qq || '--' }}</p>
          <p><strong>家庭地址:</strong> {{ profile.homeAddress || '--' }}</p>
          <p><strong>通讯地址:</strong> {{ profile.mailingAddress || '--' }}</p>
          <p><strong>婚姻情况:</strong> {{ profile.maritalStatus === 2 ? '已婚' : '未婚' }}</p>
          <p><strong>宗教信仰:</strong> {{ profile.religiousAffiliation || '--' }}</p>
          <p><strong>是否服役:</strong> {{ profile.isServedInMilitary === 1 ? '是' : '否' }}</p>
        </div>
        <div v-else class="profile-grid">
          <div><label>姓名:</label><input v-model="profile.name" /></div>
          <div><label>性别:</label><select v-model="profile.gender">
              <option value="1">男</option>
              <option value="2">女</option>
            </select></div>
          <div><label>身份证号码:</label><input v-model="profile.idCard" /></div>
          <div><label>政治面貌:</label><input v-model="profile.politicalAffiliation" /></div>
          <div><label>出生年月:</label><input v-model="profile.birthDate" type="date" /></div>
          <div><label>民族:</label><input v-model="profile.nationality" /></div>
          <div><label>身高 (cm):</label><input v-model="profile.height" type="number" /></div>
          <div><label>体重 (kg):</label><input v-model="profile.weight" type="number" /></div>
          <div><label>视力:</label><input v-model="profile.vision" /></div>
          <div><label>籍贯:</label><input v-model="profile.nativePlace" /></div>
          <div><label>联系方式:</label><input v-model="profile.telephone" /></div>
          <div><label>QQ:</label><input v-model="profile.qq" /></div>
          <div><label>家庭地址:</label><input v-model="profile.homeAddress" /></div>
          <div><label>通讯地址:</label><input v-model="profile.mailingAddress" /></div>
          <div><label>婚姻情况:</label><select v-model="profile.maritalStatus">
              <option value="2">已婚</option>
              <option value="1">未婚</option>
            </select></div>
          <div><label>宗教信仰:</label><input v-model="profile.religiousAffiliation" /></div>
          <div><label>是否服役:</label><select v-model="profile.isServedInMilitary">
              <option value="1">是</option>
              <option value="0">否</option>
            </select></div>
        </div>
      </div>

      <!-- 学业信息 -->
      <div class="profile-section">
        <h3>学业信息
          <button v-if="allEditStates" class="edit-btn"
            @click="editStates.educationInfo ? saveSection('educationInfo') : toggleEdit('educationInfo')">
            {{ editStates.educationInfo ? '保存' : '编辑' }}
          </button>
        </h3>
        <div v-if="!editStates.educationInfo">
          <div class="profile-grid">
            <p><strong>学院:</strong> {{ profile.college || '--' }}</p>
            <p><strong>专业:</strong> {{ profile.major || '--' }}</p>
            <p><strong>学号:</strong> {{ profile.studentId || '--' }}</p>
            <p><strong>文理科:</strong> {{ profile.scienceOrHumanities === 1 ? '理科' : '文科' }}</p>
            <p><strong>年级:</strong> {{ profile.grade || '--' }}</p>
            <p><strong>班级:</strong> {{ profile.className || '--' }}</p>
            <p><strong>高中毕业学校:</strong> {{ profile.highSchoolName || '--' }}</p>
            <p><strong>高中毕业地址:</strong> {{ profile.highSchoolAddress || '--' }}</p>
            <p><strong>高中文理科:</strong> {{ profile.highSchoolSubjectType === 1 ? '理科' : '文科' }}</p>
            <p><strong>高中期间总评成绩:</strong> {{ profile.highSchoolPhysicalGrade || '--' }}</p>
            <p><strong>大学期间总评成绩:</strong> {{ profile.universityPhysicalGrade || '--' }}</p>
          </div>
          <div class="education-list">
            <div v-for="(stage, index) in educationHistory" :key="index" class="education-item"
              :class="{ 'is-expanded': stage.showDetails }">
              <div class="stage-header" @click="toggleStage(index)">
                <div class="header-content">
                  <span class="stage-level">{{ stage.level }}</span>
                  <span class="school-name">{{ stage.school || '--' }}</span>
                  <span class="duration">{{ stage.startDate || '--' }} - {{ stage.endDate || '--' }}</span>
                </div>
                <span class="expand-icon">{{ stage.showDetails ? '▼' : '▶' }}</span>
              </div>
              <transition name="slide-fade">
                <div v-if="stage.showDetails" class="stage-details">
                  <div class="detail-card">
                    <div class="detail-row">
                      <label>时间周期：</label>
                      <span>{{ stage.startDate || '--' }} 至 {{ stage.endDate || '--' }}</span>
                    </div>
                  </div>
                </div>
              </transition>
            </div>
          </div>
        </div>
        <div v-else>
          <div class="profile-grid">
            <div><label>学院:</label><input v-model="profile.college" /></div>
            <div><label>专业:</label><input v-model="profile.major" /></div>
            <div><label>学号:</label><input v-model="profile.studentId" /></div>
            <div><label>文理科:</label><select v-model="profile.scienceOrHumanities">
                <option value="1">理科</option>
                <option value="2">文科</option>
              </select></div>
            <div><label>年级:</label><input v-model="profile.grade" /></div>
            <div><label>班级:</label><input v-model="profile.className" /></div>
            <div><label>高中毕业学校:</label><input v-model="profile.highSchoolName" /></div>
            <div><label>高中毕业地址:</label><input v-model="profile.highSchoolAddress" /></div>
            <div><label>高中文理科:</label><select v-model="profile.highSchoolSubjectType">
                <option value="1">理科</option>
                <option value="2">文科</option>
              </select></div>
            <div><label>高中期间总评成绩:</label><input v-model="profile.highSchoolPhysicalGrade" /></div>
            <div><label>大学期间总评成绩:</label><input v-model="profile.universityPhysicalGrade" /></div>
          </div>
          <div class="education-list">
            <div v-for="level in ['小学', '初中', '高中', '大学']" :key="level">
              <h4>{{ level }}</h4>
              <div><label>学校:</label><input :value="getEducationFieldVal(level, 'school')"
                  @input="setEducationField(level, 'school', $event.target.value)" /></div>
              <div><label>开始日期:</label><input :value="getEducationFieldVal(level, 'start')"
                  @input="setEducationField(level, 'start', $event.target.value)" type="date" /></div>
              <div><label>结束日期:</label><input :value="getEducationFieldVal(level, 'end')"
                  @input="setEducationField(level, 'end', $event.target.value)" type="date" /></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 职业与社团信息 -->
      <div class="profile-section">
        <h3>职业与社团信息
          <button v-if="allEditStates" class="edit-btn"
            @click="editStates.careerInfo ? saveSection('careerInfo') : toggleEdit('careerInfo')">
            {{ editStates.careerInfo ? '保存' : '编辑' }}
          </button>
        </h3>
        <div v-if="!editStates.careerInfo" class="profile-grid">
          <p><strong>有何职业等级证书:</strong> {{ profile.professionalCertificates || '--' }}</p>
          <p><strong>班级职务:</strong> {{ profile.classPosition || '--' }}</p>
          <p><strong>加入非军事社团名称:</strong> {{ profile.clubName || '--' }}</p>
          <p><strong>加入社团时间:</strong> {{ profile.clubJoinDate || '--' }}</p>
          <p><strong>退出社团时间:</strong> {{ profile.clubLeaveDate || '--' }}</p>
        </div>
        <div v-else class="profile-grid">
          <div><label>职业等级证书:</label><input v-model="profile.professionalCertificates" /></div>
          <div><label>班级职务:</label><input v-model="profile.classPosition" /></div>
          <div><label>非军事社团名称:</label><input v-model="profile.clubName" /></div>
          <div><label>加入社团时间:</label><input v-model="profile.clubJoinDate" type="date" /></div>
          <div><label>退出社团时间:</label><input v-model="profile.clubLeaveDate" type="date" /></div>
        </div>
      </div>

      <!-- 军事兴趣类社团信息 -->
      <div class="profile-section">
        <h3>军事兴趣类社团信息
          <button v-if="allEditStates" class="edit-btn"
            @click="editStates.militaryClubInfo ? saveSection('militaryClubInfo') : toggleEdit('militaryClubInfo')">
            {{ editStates.militaryClubInfo ? '保存' : '编辑' }}
          </button>
        </h3>
        <div v-if="!editStates.militaryClubInfo" class="profile-grid">
          <p><strong>是否有病史:</strong> {{ profile.hasMedicalHistory === 1 ? '有' : '没有' }}</p>
          <p><strong>身体状况:</strong> {{ profile.physicalCondition === 1 ? '良好' : (profile.physicalCondition === 2 ? '一般'
            : '较差') }}</p>
          <p><strong>心理访谈情况:</strong> {{ profile.psychologicalInterview || '--' }}</p>
          <p><strong>是否参加过军事训练:</strong> {{ profile.hasMilitaryTraining === 1 ? '是' : '否' }}</p>
          <p><strong>参加军事训练时长:</strong> {{ profile.militaryTrainingDuration ? profile.militaryTrainingDuration + ' 天' :
            '--' }}</p>
          <p><strong>退出军事兴趣社团时间:</strong> {{ profile.militaryClubLeaveDate || '--' }}</p>
          <p><strong>退出社团发展情况:</strong> {{ profile.militaryClubLeaveDevelop || '--' }}</p>
          <p><strong>是否军事兴趣类社团成员:</strong> {{ profile.isMilitaryClubMember === 1 ? '是' : '否' }}</p>
          <p><strong>加入时间:</strong> {{ profile.militaryClubJoinDate || '--' }}</p>
          <p><strong>所在军事兴趣社团名称:</strong> {{ profile.militaryClubName || '--' }}</p>
          <p><strong>在军事兴趣社团担任职务:</strong> {{ profile.militaryClubPosition || '--' }}</p>
        </div>
        <div v-else class="profile-grid">
          <div><label>是否有病史:</label><select v-model="profile.hasMedicalHistory">
              <option value="1">有</option>
              <option value="0">没有</option>
            </select></div>
          <div><label>身体状况:</label><select v-model="profile.physicalCondition">
              <option value="1">良好</option>
              <option value="2">一般</option>
              <option value="3">较差</option>
            </select></div>
          <div><label>心理访谈情况:</label><textarea v-model="profile.psychologicalInterview" /></div>
          <div><label>是否参加过军事训练:</label><select v-model="profile.hasMilitaryTraining">
              <option value="1">是</option>
              <option value="0">否</option>
            </select></div>
          <div><label>军事训练时长 (天):</label><input v-model="profile.militaryTrainingDuration" type="number" /></div>
          <div><label>退出军事兴趣社团时间:</label><input v-model="profile.militaryClubLeaveDate" type="date" /></div>
          <div><label>退出社团发展情况:</label><input v-model="profile.militaryClubLeaveDevelop" /></div>
          <div><label>是否军事兴趣类社团成员:</label><select v-model="profile.isMilitaryClubMember">
              <option value="1">是</option>
              <option value="0">否</option>
            </select></div>
          <div><label>加入时间:</label><input v-model="profile.militaryClubJoinDate" type="date" /></div>
          <div><label>军事兴趣社团名称:</label><input v-model="profile.militaryClubName" /></div>
          <div><label>社团职务:</label><input v-model="profile.militaryClubPosition" /></div>
        </div>
      </div>

      <!-- 服役信息 -->
      <div class="profile-section" v-if="profile.isServedInMilitary">
        <h3>服役信息
          <button v-if="allEditStates" class="edit-btn"
            @click="editStates.serviceInfo ? saveSection('serviceInfo') : toggleEdit('serviceInfo')">
            {{ editStates.serviceInfo ? '保存' : '编辑' }}
          </button>
        </h3>
        <div v-if="!editStates.serviceInfo" class="profile-grid">
          <p><strong>入伍军种:</strong> {{ profile.militaryBranch || '--' }}</p>
          <p><strong>部队编号:</strong> {{ profile.unitNumber || '--' }}</p>
          <p><strong>军衔:</strong> {{ profile.rankname || '--' }}</p>
          <p><strong>第一次报名应征时间:</strong> {{ profile.firstEnlistmentDate || '--' }}</p>
          <p><strong>入伍时间:</strong> {{ profile.enlistmentDate || '--' }}</p>
          <p><strong>入伍地点:</strong> {{ profile.enlistmentPlace || '--' }}</p>
          <p><strong>退役时间:</strong> {{ profile.dischargeDate || '--' }}</p>
          <p><strong>部队专业:</strong> {{ profile.militarySpecialty || '--' }}</p>
          <p><strong>部队职务:</strong> {{ profile.militaryPosition || '--' }}</p>
          <p><strong>获得奖项:</strong> {{ profile.awards || '--' }}</p>
          <p><strong>是否有预备役:</strong> {{ profile.isReservedMilitary === 1 ? '是' : '否' }}</p>
          <p><strong>预备役职务:</strong> {{ profile.ReservedPosition || '--' }}</p>
          <p><strong>预备役专业:</strong> {{ profile.ReservedSpecialty || '--' }}</p>
        </div>
        <div v-else class="profile-grid">
          <div><label>入伍军种:</label><input v-model="profile.militaryBranch" /></div>
          <div><label>部队编号:</label><input v-model="profile.unitNumber" /></div>
          <div><label>军衔:</label><input v-model="profile.rankname" /></div>
          <div><label>第一次报名应征时间:</label><input v-model="profile.firstEnlistmentDate" type="date" /></div>
          <div><label>入伍时间:</label><input v-model="profile.enlistmentDate" type="date" /></div>
          <div><label>入伍地点:</label><input v-model="profile.enlistmentPlace" /></div>
          <div><label>退役时间:</label><input v-model="profile.dischargeDate" type="date" /></div>
          <div><label>部队专业:</label><input v-model="profile.militarySpecialty" /></div>
          <div><label>部队职务:</label><input v-model="profile.militaryPosition" /></div>
          <div><label>获得奖项:</label><input v-model="profile.awards" /></div>
          <div><label>是否有预备役:</label><select v-model="profile.isReservedMilitary">
              <option value="1">是</option>
              <option value="0">否</option>
            </select></div>
          <div><label>预备役职务:</label><input v-model="profile.ReservedPosition" /></div>
          <div><label>预备役专业:</label><input v-model="profile.ReservedSpecialty" /></div>
        </div>
      </div>

      <!-- 预征预储情况 -->
      <div class="profile-section">
        <h3>预征预储情况
          <button v-if="allEditStates" class="edit-btn"
            @click="editStates.preReserveInfo ? saveSection('preReserveInfo') : toggleEdit('preReserveInfo')">
            {{ editStates.preReserveInfo ? '保存' : '编辑' }}
          </button>
        </h3>
        <div v-if="!editStates.preReserveInfo" class="profile-grid">
          <p><strong>军事技能训练情况:</strong> {{ profile.militarySkillsTraining || '--' }}</p>
          <p><strong>政治理论学习情况:</strong> {{ profile.politicalTheoryLearningSituation || '--' }}</p>
          <p><strong>体适能训练情况:</strong> {{ profile.physicalFitnessTraining || '--' }}</p>
          <p><strong>体检检查情况:</strong> {{ profile.physicalExamination || '--' }}</p>
          <p><strong>心理测验情况:</strong> {{ profile.psychologicalTestSituation || '--' }}</p>
        </div>
        <div v-else class="profile-grid">
          <div><label>军事技能训练情况:</label><textarea v-model="profile.militarySkillsTraining"></textarea></div>
          <div><label>政治理论学习情况:</label><textarea v-model="profile.politicalTheoryLearningSituation"></textarea></div>
          <div><label>体适能训练情况:</label><textarea v-model="profile.physicalFitnessTraining"></textarea></div>
          <div><label>体检检查情况:</label><textarea v-model="profile.physicalExamination"></textarea></div>
          <div><label>心理测验情况:</label><textarea v-model="profile.psychologicalTestSituation"></textarea></div>
        </div>
      </div>

      <!-- 体测信息 -->
      <div class="profile-section">
        <h3>体测信息
          <button v-if="allEditStates" class="edit-btn"
            @click="editStates.physicalTestInfo ? saveSection('physicalTestInfo') : toggleEdit('physicalTestInfo')">
            {{ editStates.physicalTestInfo ? '保存' : '编辑' }}
          </button>
        </h3>
        <div v-if="!editStates.physicalTestInfo">
          <h4>体能训练情况</h4>
          <span v-if="profile.physicalTestVOList?.length" @click="changePhysicalTable()">
            {{ isPhysicalTable ? '收起▼' : '点击展开▶' }}
          </span>
          <div v-if="profile.physicalTestVOList?.length && isPhysicalTable" class="table-container">
            <table class="compare-table">
              <thead>
                <tr>
                  <th colspan="1" rowspan="2">项目</th>
                  <th :colspan="profile.physicalTestVOList.length * 2" class="main-header">体能测试成绩</th>
                </tr>
                <tr>
                  <template v-for="test in profile.physicalTestVOList" :key="test.testYear">
                    <th colspan="2">{{ test.testYear || '--' }}</th>
                  </template>
                </tr>
                <tr>
                  <th>测试项</th>
                  <template v-for="test in profile.physicalTestVOList" :key="test.testYear">
                    <th>成绩</th>
                    <th>分数</th>
                  </template>
                </tr>
              </thead>
              <tbody>
                <template v-for="(item, index) in physicalItems" :key="index">
                  <tr>
                    <td class="item-name">{{ item.label }}</td>
                    <template v-for="test in profile.physicalTestVOList" :key="test.testYear">
                      <td>{{ getTestValue(test, item.key) || '--' }}</td>
                      <td>{{ getTestScore(test, item.key) || '--' }}</td>
                    </template>
                  </tr>
                </template>
                <tr class="summary-row">
                  <td>考核结果</td>
                  <template v-for="test in profile.physicalTestVOList" :key="test.testYear">
                    <td colspan="2" class="result-cell">{{ test.testGrade || '--' }}</td>
                  </template>
                </tr>
              </tbody>
            </table>
          </div>
          <div v-else class="no-data">暂无体测数据</div>
        </div>
        <div v-else>
          <div v-if="profile.physicalTestVOList?.length" class="table-container">
            <table class="compare-table">
              <thead>
                <tr>
                  <th>测试年份</th>
                  <th v-for="item in physicalItems" :key="item.key">{{ item.label }}</th>
                  <th>考核结果</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(test, testIndex) in profile.physicalTestVOList" :key="testIndex">
                  <td><input v-model="test.testYear" placeholder="年份" /></td>
                  <td v-for="item in physicalItems" :key="item.key">
                    <input v-model="test[item.key]" :placeholder="item.label" />
                  </td>
                  <td><input v-model="test.testGrade" placeholder="考核结果" /></td>
                </tr>
              </tbody>
            </table>
          </div>
          <div v-else class="no-data">暂无体测数据</div>
        </div>
      </div>

      <!-- 相关图片 -->
      <div class="profile-section">
        <h3>相关图片</h3>
        <div class="image-gallery">
          <img v-for="(image, index) in profile.images" :key="index" :src="image" alt="相关图片"
            class="profile-image-gallery" />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getPersonInfo, getExcle, getPdf } from '@/api/pre-reserve/personal-info';
import { updatePersonInfo } from '@/api/pre-reserve/personal-info';

const studentId = useRoute().query.studentId;
const profile = ref<any>({});
const isPhysicalTable = ref(true);
const allEditStates = ref(false);
const editStates = ref({
  basicInfo: false,
  educationInfo: false,
  careerInfo: false,
  militaryClubInfo: false,
  serviceInfo: false,
  preReserveInfo: false,
  physicalTestInfo: false,
});

function handleAllEditStates() {
  allEditStates.value = !allEditStates.value;

  if (!allEditStates.value) {
    editStates.value.basicInfo = false;
    editStates.value.educationInfo = false;
    editStates.value.careerInfo = false;
    editStates.value.militaryClubInfo = false;
    editStates.value.serviceInfo = false;
    editStates.value.preReserveInfo = false;
    editStates.value.physicalTestInfo = false;
  }
}

// 体测项目配置
const physicalItems = [
  { label: '身高', key: 'height', unit: 'cm' },
  { label: '体重', key: 'weight', unit: 'kg' },
  { label: 'BMI', key: 'bmi' },
  { label: '左眼裸眼视力', key: 'leftEyeVision' },
  { label: '右眼裸眼视力', key: 'rightEyeVision' },
  { label: '左眼串镜检查', key: 'leftEyeLens' },
  { label: '右眼串镜检查', key: 'rightEyeLens' },
  { label: '左眼屈光不正', key: 'leftEyeRefraction' },
  { label: '右眼屈光不正', key: 'rightEyeRefraction' },
  { label: '肺活量', key: 'lungCapacity', unit: 'ml' },
  { label: '50米跑', key: 'fiftyMeter', unit: '秒' },
  { label: '立定跳远', key: 'standingJump', unit: 'cm' },
  { label: '坐位体前屈', key: 'sitReach', unit: 'cm' },
  { label: '800米跑', key: 'eightHundredMeter', unit: '秒' },
  { label: '1000米跑', key: 'oneThousandMeter', unit: '秒' },
  { label: '仰卧起坐', key: 'sitUps', unit: '次' },
  { label: '引体向上', key: 'pullUps', unit: '次' },
  { label: '体育分数', key: 'peScore' },
];

// 学业历程
const educationHistory = computed(() => {
  return [
    {
      level: '小学',
      school: profile.value.primarySchoolName || '--',
      startDate: profile.value.primarySchoolStartDate || '--',
      endDate: profile.value.primarySchoolEndDate || '--',
      showDetails: false,
    },
    {
      level: '初中',
      school: profile.value.middleSchoolName || '--',
      startDate: profile.value.middleSchoolStartDate || '--',
      endDate: profile.value.middleSchoolEndDate || '--',
      showDetails: false,
    },
    {
      level: '高中',
      school: profile.value.highSchoolName || '--',
      startDate: profile.value.highSchoolStartDate || '--',
      endDate: profile.value.highSchoolEndDate || '--',
      showDetails: false,
    },
    {
      level: '大学',
      school: profile.value.universityName || '--',
      startDate: profile.value.universityStartDate || '--',
      endDate: profile.value.universityEndDate || '--',
      showDetails: false,
    },
  ];
});

// 获取学业历程字段值
const getEducationFieldVal = (level: string, field: string) => {
  const fieldMap: { [key: string]: { school: string; start: string; end: string } } = {
    小学: { school: 'primarySchoolName', start: 'primarySchoolStartDate', end: 'primarySchoolEndDate' },
    初中: { school: 'middleSchoolName', start: 'middleSchoolStartDate', end: 'middleSchoolEndDate' },
    高中: { school: 'highSchoolName', start: 'highSchoolStartDate', end: 'highSchoolEndDate' },
    大学: { school: 'universityName', start: 'universityStartDate', end: 'universityEndDate' },
  };
  return profile.value[fieldMap[level][field]] || '';
};

// 设置学业历程字段值
const setEducationField = (level: string, field: string, value: string) => {
  const fieldMap: { [key: string]: { school: string; start: string; end: string } } = {
    小学: { school: 'primarySchoolName', start: 'primarySchoolStartDate', end: 'primarySchoolEndDate' },
    初中: { school: 'middleSchoolName', start: 'middleSchoolStartDate', end: 'middleSchoolEndDate' },
    高中: { school: 'highSchoolName', start: 'highSchoolStartDate', end: 'highSchoolEndDate' },
    大学: { school: 'universityName', start: 'universityStartDate', end: 'universityEndDate' },
  };
  profile.value[fieldMap[level][field]] = value;
};

// 切换编辑状态
const toggleEdit = (section: string) => {
  editStates.value[section] = !editStates.value[section];
};

// 保存板块数据
const saveSection = async (section: string) => {
  try {
    let dataToSend: any = {};
    let type = '';
    switch (section) {
      case 'basicInfo':
        dataToSend = {
          name: profile.value.name,
          gender: profile.value.gender,
          idCard: profile.value.idCard,
          politicalAffiliation: profile.value.politicalAffiliation,
          birthDate: profile.value.birthDate,
          nationality: profile.value.nationality,
          height: profile.value.height,
          weight: profile.value.weight,
          vision: profile.value.vision,
          nativePlace: profile.value.nativePlace,
          telephone: profile.value.telephone,
          qq: profile.value.qq,
          homeAddress: profile.value.homeAddress,
          mailingAddress: profile.value.mailingAddress,
          maritalStatus: profile.value.maritalStatus,
          religiousAffiliation: profile.value.religiousAffiliation,
          isServedInMilitary: profile.value.isServedInMilitary,
        };
        break;
      case 'educationInfo':
        dataToSend = {
          college: profile.value.college,
          major: profile.value.major,
          studentId: profile.value.studentId,
          scienceOrHumanities: profile.value.scienceOrHumanities,
          grade: profile.value.grade,
          className: profile.value.className,
          highSchoolName: profile.value.highSchoolName,
          highSchoolAddress: profile.value.highSchoolAddress,
          highSchoolSubjectType: profile.value.highSchoolSubjectType,
          highSchoolPhysicalGrade: profile.value.highSchoolPhysicalGrade,
          universityPhysicalGrade: profile.value.universityPhysicalGrade,
          primarySchoolName: profile.value.primarySchoolName,
          primarySchoolStartDate: profile.value.primarySchoolStartDate,
          primarySchoolEndDate: profile.value.primarySchoolEndDate,
          middleSchoolName: profile.value.middleSchoolName,
          middleSchoolStartDate: profile.value.middleSchoolStartDate,
          middleSchoolEndDate: profile.value.middleSchoolEndDate,
          highSchoolStartDate: profile.value.highSchoolStartDate,
          highSchoolEndDate: profile.value.highSchoolEndDate,
          universityName: profile.value.universityName,
          universityStartDate: profile.value.universityStartDate,
          universityEndDate: profile.value.universityEndDate,
        };
        break;
      case 'careerInfo':
        dataToSend = {
          professionalCertificates: profile.value.professionalCertificates,
          classPosition: profile.value.classPosition,
          clubName: profile.value.clubName,
          clubJoinDate: profile.value.clubJoinDate,
          clubLeaveDate: profile.value.clubLeaveDate,
        };
        break;
      case 'militaryClubInfo':
        dataToSend = {
          hasMedicalHistory: profile.value.hasMedicalHistory,
          physicalCondition: profile.value.physicalCondition,
          psychologicalInterview: profile.value.psychologicalInterview,
          hasMilitaryTraining: profile.value.hasMilitaryTraining,
          militaryTrainingDuration: profile.value.militaryTrainingDuration,
          militaryClubLeaveDate: profile.value.militaryClubLeaveDate,
          militaryClubLeaveDevelop: profile.value.militaryClubLeaveDevelop,
          isMilitaryClubMember: profile.value.isMilitaryClubMember,
          militaryClubJoinDate: profile.value.militaryClubJoinDate,
          militaryClubName: profile.value.militaryClubName,
          militaryClubPosition: profile.value.militaryClubPosition,
        };
        break;
      case 'serviceInfo':
        dataToSend = {
          militaryBranch: profile.value.militaryBranch,
          unitNumber: profile.value.unitNumber,
          rankname: profile.value.rankname,
          firstEnlistmentDate: profile.value.firstEnlistmentDate,
          enlistmentDate: profile.value.enlistmentDate,
          enlistmentPlace: profile.value.enlistmentPlace,
          dischargeDate: profile.value.dischargeDate,
          militarySpecialty: profile.value.militarySpecialty,
          militaryPosition: profile.value.militaryPosition,
          awards: profile.value.awards,
          isReservedMilitary: profile.value.isReservedMilitary,
          ReservedPosition: profile.value.ReservedPosition,
          ReservedSpecialty: profile.value.ReservedSpecialty,
        };
        break;
      case 'preReserveInfo':
        dataToSend = {
          militarySkillsTraining: profile.value.militarySkillsTraining,
          politicalTheoryLearningSituation: profile.value.politicalTheoryLearningSituation,
          physicalFitnessTraining: profile.value.physicalFitnessTraining,
          physicalExamination: profile.value.physicalExamination,
          psychologicalTestSituation: profile.value.psychologicalTestSituation,
        };
        break;
      case 'physicalTestInfo':
        dataToSend = { physicalTestVOList: profile.value.physicalTestVOList };
        break;
    }
    await updatePersonInfo(profile.value.userId, dataToSend);
    ElMessage.success(`${section} 保存成功！`);
    editStates.value[section] = false;
  } catch (error) {
    console.error(`${section} 保存失败:`, error);
    ElMessage.error(`${section} 保存失败！`);
  }
};

// 挂载时
onMounted(() => {
  getPersonInfo(studentId)
    .then((response) => {
      profile.value = response.data;
    })
    .catch((error) => {
      console.error('请求失败:', error);
      ElMessage.error('请求失败！');
    });
});

// 切换体测表格显示
const changePhysicalTable = () => {
  isPhysicalTable.value = !isPhysicalTable.value;
};

// 获取体测数值
const getTestValue = (test, key) => {
  const item = physicalItems.find((i) => i.key === key);
  if (!test[key]) return '--';
  return item?.unit ? `${test[key]}${item.unit}` : test[key];
};

// 获取体测分数
const getTestScore = (test, key) => {
  const scoreKeys = {
    height: 'heightWeightScore',
    weight: 'heightWeightScore',
    bmi: 'heightWeightScore',
    leftEyeVision: null,
    rightEyeVision: null,
    leftEyeLens: null,
    rightEyeLens: null,
    leftEyeRefraction: null,
    rightEyeRefraction: null,
    lungCapacity: 'lungCapacityScore',
    fiftyMeter: 'fiftyMeterScore',
    standingJump: 'standingJumpScore',
    sitReach: 'sitReachScore',
    eightHundredMeter: 'enduranceRunScore',
    oneThousandMeter: 'enduranceRunScore',
    sitUps: 'strengthScore',
    pullUps: 'strengthScore',
    peScore: null,
  };
  return scoreKeys[key] ? test[scoreKeys[key]] || '--' : '--';
};

// 切换学业阶段显示
const toggleStage = (index: number) => {
  educationHistory.value[index].showDetails = !educationHistory.value[index].showDetails;
};

// 获取水印样式
const getWatermarkStyle = (index: number) => {
  const top = Math.random() * 100;
  const left = Math.random() * 100;
  const rotate = Math.random() * 60 - 30;
  return {
    top: `${top}%`,
    left: `${left}%`,
    transform: `rotate(${rotate}deg)`,
    fontSize: `${Math.random() * 10 + 12}px`,
    opacity: Math.random() * 0.2 + 0.1,
  };
};

// 返回上一页
const goBack = () => {
  window.history.back();
};

// 导出为Excel
const exportToExcel = () => {
  ElMessage.success('正在导出,请稍等！');
  getExcle(studentId);
};

// 导出为PDF
const exportToPdf = () => {
  const data = { studentIds: [studentId] };
  ElMessage.success('正在导出,请稍等！');
  getPdf(data);
};
</script>

<style scoped>
.page-wrapper {
  position: relative;
  min-width: 970px;
}

.watermarks {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 10;
}

.watermark {
  position: absolute;
  color: rgba(15, 14, 14, 0.15);
  white-space: nowrap;
  user-select: none;
}

.top-bar {
  padding: 10px 0;
}

.back-btn,
.export-btn,
.allEdit-btn,
.edit-btn {
  margin: 10px;
  padding: 8px 16px;
  font-size: 14px;
  border: none;
  background-color: #00aaff;
  color: white;
  cursor: pointer;
  border-radius: 5px;
}

.export-btn {
  background-color: #4caf50;
}

.edit-btn {
  background-color: brown;
  float: right;
  margin: 0;
  margin-left: 1rem;
}

.back-btn:hover,
.export-btn:hover,
.edit-btn:hover {
  opacity: 0.8;
}

.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.profile-title {
  text-align: center;
  font-size: 26px;
  font-weight: bold;
  margin-bottom: 20px;
}

.profile-header {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.profile-image {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #007bff;
}

.profile-section {
  margin-bottom: 20px;
  background: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  position: relative;
}

.profile-section h3 {
  font-size: 22px;
  color: #007bff;
  margin-bottom: 15px;
  border-left: 4px solid #007bff;
  padding-left: 10px;
  display: inline-block;
}

.profile-section h4 {
  font-size: 17px;
  color: #000000;
  margin-bottom: 10px;
  margin-top: 15px;
  padding-left: 8px;
}

.profile-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  padding: 10px;
  background: #f9f9f9;
  border-radius: 8px;
}

.profile-grid p {
  margin: 5px 0;
  line-height: 1.6;
  font-size: 17px;
  color: #333;
}

.profile-grid strong {
  font-weight: bold;
  color: #555;
}

.profile-grid div {
  display: flex;
  flex-direction: column;
}

.profile-grid label {
  font-weight: bold;
  color: #555;
  margin-bottom: 5px;
}

.profile-grid input,
.profile-grid select,
.profile-grid textarea {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.profile-grid textarea {
  resize: vertical;
  min-height: 80px;
}

/* 学业历程样式 */
.education-list {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  margin-top: 15px;
}

.education-item {
  border-bottom: 1px solid #eee;
  transition: all 0.3s ease;
}

.education-item:last-child {
  border-bottom: none;
}

.stage-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: #f8f9fa;
  cursor: pointer;
  transition: background 0.2s;
}

.stage-header:hover {
  background: #f1f3f5;
}

.header-content {
  display: flex;
  gap: 20px;
  align-items: center;
}

.stage-level {
  font-weight: 600;
  min-width: 60px;
  color: #007bff;
}

.school-name {
  font-weight: 500;
  color: #2c3e50;
}

.duration {
  color: #666;
  font-size: 0.9em;
}

.expand-icon {
  font-size: 0.8em;
  color: #666;
}

.stage-details {
  padding: 16px 20px;
  background: #fff;
  border-top: 1px solid #eee;
}

.detail-card {
  display: grid;
  gap: 16px;
  padding: 16px;
  background: #fcfcfc;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.detail-row {
  display: grid;
  grid-template-columns: 100px 1fr;
  gap: 12px;
  align-items: start;
}

.detail-row label {
  font-weight: 500;
  color: #666;
}

.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.2s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

/* 体测表格样式 */
.table-container {
  overflow-x: auto;
  margin: 20px 0;
  border: 1px solid #e0e0e0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.compare-table {
  width: 100%;
  min-width: 800px;
  border-collapse: collapse;
  background: white;
}

.compare-table th {
  background: #f8f9fa;
  font-weight: 600;
  padding: 12px 15px;
  border: 1px solid #ddd;
}

.main-header {
  background: #007bff !important;
  color: white;
  font-size: 16px;
}

.item-name {
  font-weight: 500;
  background: #f4f4f4;
}

.compare-table td {
  padding: 10px 15px;
  border: 1px solid #eee;
  text-align: center;
  min-width: 80px;
}

.compare-table input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.summary-row td {
  background: #fff3cd;
  font-weight: bold;
}

.result-cell {
  color: #d35400;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #666;
  font-size: 16px;
}

/* 图片展示样式 */
.image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
}

.profile-image-gallery {
  width: 150px;
  height: 100px;
  object-fit: cover;
  border-radius: 8px;
}
</style>